package com.github.xzb617.rpc.loadbalancer.strategy;

import com.github.xzb617.rpc.entity.Server;
import com.github.xzb617.rpc.loadbalancer.AbstractLoadBalancer;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 基于权重的顺序轮询策略
 */
public class WeightRoundRobinLoadBalancer extends RoundRobinLoadBalancer {

    public Server chooseServer(List<Server> servers) {
        List<Server> weightServers = this.recalculateServerListByWeight(servers);
        return super.chooseServer(weightServers);
    }

    /**
     * 根据权重重新计算服务列表
     */
    private List<Server> recalculateServerListByWeight(List<Server> servers) {
        List<Server> weightServers = new ArrayList<Server>();
        Iterator<Server> it = servers.iterator();
        while (it.hasNext()) {
            Server server = it.next();
            int weight = server.getWeight();
            for (int i = 0; i < weight; i++) {
                weightServers.add(server);
            }
        }
        return weightServers;
    }
}
